package gw.com.android.ui.trade;

import android.app.Activity;
import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.sharesdk.framework.PlatformActionListener;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdsData;
import gw.com.android.ui.dialog.SharePopWindow;
import www.com.library.model.DataItemDetail;

/**
 * 市价开仓、平仓结果的广告位处理
 *
 * @author jett
 * @since 2017-09-06.
 */
public class AdvertiseHandler {

    private static final List<String> supports = new ArrayList<>();

    static {
        supports.add(AdsConfigPresenter.TYPE_CREATE_ORDER_FAILED);//开仓失败
        supports.add(AdsConfigPresenter.TYPE_CREATE_ORDER_SUCCESS);//开仓成功
        supports.add(AdsConfigPresenter.TYPE_CLOSE_ORDER_SUCCESS);//平仓成功
        supports.add(AdsConfigPresenter.TYPE_CLOSE_ORDER_PROFIT);//平仓成功并盈利
    }

    private boolean enable = false;
    private DataItemDetail mItem;

    public AdvertiseHandler(String tag) {
        if (!supports.contains(tag)) {
            return;
        }
        enable = parseJson(tag);
    }

    public boolean isEnable() {
        return enable;
    }

    public void handle(final Activity activity, ImageView iv) {
        if (enable && mItem != null) {
            String url = mItem.getString("url");
            if (TextUtils.isEmpty(url)) {
                return;
            }
            iv.setVisibility(View.VISIBLE);
            // 广告图片要求不缓存
            Glide.with(activity).load(url).error(R.mipmap.a_default_adtrade).diskCacheStrategy(DiskCacheStrategy.NONE).into(iv);
            String category = mItem.getString("category");
            if ("1".equals(category)) {
                setLinkListener(activity, mItem, iv);
            } else if ("2".equals(category)) {
                setShareListener(activity, mItem, iv);
            }
        }
    }

    public void handleProfit(final Activity activity, ImageView iv, double profitAmount, PlatformActionListener listener) {
        if (enable && mItem != null) {
            String url = mItem.getString("url");
            if (TextUtils.isEmpty(url)) {
                return;
            }
            iv.setVisibility(View.VISIBLE);
            // 广告图片要求不缓存
            Glide.with(activity).load(url).error(R.mipmap.a_default_adtrade).diskCacheStrategy(DiskCacheStrategy.NONE).into(iv);
            String category = mItem.getString("category");
            if ("1".equals(category)) {
                setLinkListener(activity, mItem, iv);
            } else if ("2".equals(category)) {
                setShareListener(activity, mItem, iv, profitAmount, listener);
            }
        }
    }

    private void setLinkListener(final Activity activity, DataItemDetail item, ImageView iv) {
        final String link = item.getString("link");
        final String title = item.getString("title");
        if (!TextUtils.isEmpty(link)) {
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DataItemDetail mItem = new DataItemDetail();
                    mItem.setStringValue(ConfigType.CONFIG_TYPE_TYPE_URL_TAG, link);
                    if (!TextUtils.isEmpty(title)) {
                        mItem.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, title);
                    }
                    ActivityManager.showWebPageActivity(activity, mItem, AppMain.getAppString(R.string.btn_back));
                }
            });
        }
    }

    private void setShareListener(final Activity activity, final DataItemDetail item, ImageView iv) {
        final String title = item.getString("title");
        final String content = item.getString("content");
        final String link = item.getString("link");
        final String imageUrl = item.getString("url");

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SharePopWindow(activity, AppContances.SHARE_PROFIT_TYPE, null, item, new SharePopWindow.ShareCallback() {
                    @Override
                    public void onClick(final int position, DataItemDetail itemDetail, SharePopWindow popWindow) {
                        popWindow.onShareFun(popWindow.getTitleId(position),
                                title,
                                content,
                                ConfigUtil.getDealStrUrl(link), imageUrl, null);
                    }
                }).show();
            }
        });
    }

    private void setShareListener(final Activity activity, final DataItemDetail item, ImageView iv, double profitAmount, final PlatformActionListener listener) {
        String stub = String.valueOf(profitAmount) + (DataManager.instance().isCNY() ? "元" : "美刀");
        final String title = String.format(Locale.getDefault(), "我在富通环球投资又赚了%s！", stub);
        final String content = String.format(Locale.getDefault(), "我在富通环球投资，刚刚这一单又小赚%s，感觉自己就要成为人生赢家！", stub);
        //final String link = item.getString("link");
        String mUrl = ConfigUtil.instance().getUrlPath(ConfigType.LOTTERY_SHARE_TAG);
        final String link = mUrl + "&profit=" + profitAmount + "&currency=" + (DataManager.instance().isCNY() ? "CNY" : "USD");
        final String imageUrl = item.getString("url");

        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SharePopWindow(activity, AppContances.SHARE_PROFIT_TYPE, null, item, new SharePopWindow.ShareCallback() {
                    @Override
                    public void onClick(final int position, DataItemDetail itemDetail, SharePopWindow popWindow) {
                        popWindow.onShareFun(popWindow.getTitleId(position),
                                title,
                                content,
                                link, imageUrl, listener);
                    }
                }).title(getShareTitle()).show();
            }
        });
    }

    private CharSequence getShareTitle() {
        String content = "分享给好友，好友可得";
        String amount = "5美元";
        SpannableStringBuilder ssb = new SpannableStringBuilder(content + amount);
        ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
        ssb.setSpan(span, content.length(), content.length() + amount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ssb;
    }

    private boolean parseJson(String tag) {
        AdsData data = AdsConfigPresenter.getInstance().getAd(tag);
        if (data == null || data.adPics == null || data.adPics.isEmpty()) {
            return false;
        }
        AdsData.PicData picData = data.adPics.get(0);
        if (picData == null) {
            return false;
        }
        mItem = new DataItemDetail();
        mItem.setStringValue("id", data.id);
        mItem.setStringValue("category", data.category);
        mItem.setStringValue("content", data.content);
        mItem.setStringValue("link", picData.link);
        mItem.setStringValue("title", picData.title);
        mItem.setStringValue("url", picData.url);
        return true;
    }

}
